package me.quexi.georgia.observer;

import java.util.ArrayList;
import java.util.HashMap;

import me.quexi.georgia.interfaces.IFacade;
import me.quexi.georgia.interfaces.INotification;
import me.quexi.georgia.interfaces.INotifyResponder;
import me.quexi.georgia.vo.HttpContext;

public class Facade implements IFacade {

	private HashMap<Integer, ArrayList<INotifyResponder>> _observerMap = null;
	
	public Facade()
	{
		_observerMap = new HashMap<Integer, ArrayList<INotifyResponder>>();
	}
	
	@Override
	public Boolean registerResponder(INotifyResponder responder) 
	{
		ArrayList<Integer> notificationList = responder.getNotificationList();
		
		// 注册所有监听者
		for(int i = 0; i < notificationList.size(); i ++)
		{
			int type = notificationList.get(i);
			ArrayList<INotifyResponder> observers = _observerMap.get(type);
			if(observers != null)
			{
				if(!observers.contains(responder)) observers.add(responder);
				else throw new Error("消息"+type+"重复侦听");
			}
			else
			{
				observers = new ArrayList<INotifyResponder>();
				observers.add(responder);
			}
		}
		return true;
	}

	@Override
	public void sendNotification(int notification, HashMap<String, Object> body, HttpContext httContext)
	{
		notifyObservers(new Notification(notification, body, httContext));
	}
	
//	@Override
//	public void sendNotification(String notification)
//	{
//		notifyObservers(new Notification(notification, null));
//	}
	
	
	
	/**
	 * 通知观察者
	 * @param notification 
	 */		
	private void notifyObservers(INotification notification)
	{
		ArrayList<INotifyResponder> observers = _observerMap.get(notification.getName());
		if(observers != null)
		{
			// 通知所有侦听这个消息的观察者
			for(int i = 0; i < observers.size(); i ++)
			{
				INotifyResponder responder = observers.get(i);
				responder.notifyHandler(notification);
			}
		}
	}

}
